package app.softtech.freechat;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import app.softtech.freechat.adapter.UserListViewAdapter;
import app.softtech.freechat.database.DatabaseUser;

/**
 * Class used to get friend online and request add new friend
 * @author LocDev
 *
 */
public class ActivitySearchFriendOnline extends Activity {
	private static final String TAG = ActivitySearchFriendOnline.class.getSimpleName();
	
	String username;
	private List<DatabaseUser> mUserList = new ArrayList<DatabaseUser>();

	private ListView mUserListView;
	private TextView mTextView;
	private Button mButton;
	private UserListViewAdapter mAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_friendlist_or_recent);

		mUserListView = (ListView) findViewById(R.id.lv_friendlist_or_recent);
		mTextView = (TextView) findViewById(R.id.tv_no_result_search_hint);
		mButton = (Button) findViewById(R.id.btn_search_friend_online);

		mTextView.setVisibility(View.GONE);
		mButton.setVisibility(View.GONE);

		username = getIntent().getExtras().getString(Constants.USERNAME);
		new GetUserOnServer().execute(username);

		mUserListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String userId = getSharedPreferences(Constants.PROJECT_PREFS, Context.MODE_PRIVATE).getString(Constants.USER_ID, "");
				String userRequestId = String.valueOf(mUserList.get(position).getUserId());
				String regId = getSharedPreferences(Constants.PROJECT_PREFS, Context.MODE_PRIVATE).getString(Constants.PROPERTY_REG_ID, "");
				Log.i(TAG, "User id: " + userId + " user request id: " + userRequestId + " Reg id: " + regId);
				SendFriendRequest send = new SendFriendRequest(userId, userRequestId, regId);
				send.execute();
			}
		});
	}
	
	/**
	 * Function used to get all user on server if server contained user name like parameter user name
	 * @param username
	 * @return null if user name does not exists on server, otherwise return JSONArray contained database of user
	 */
	public JSONArray getListUserOnServer(String username) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Constants.USERNAME, username));

		HttpRequest request = new HttpRequest();
		String result = request.makeServiceCall(Constants.URL_SEARCH_USER, HttpRequest.POST, params);
		try {
			JSONObject jsonObj = new JSONObject(result);
			if (Integer.parseInt(jsonObj.getString(Constants.KEY_SUCCESS)) == 1) {
				JSONArray jsonArray = jsonObj.getJSONArray("data");
				return jsonArray;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * Create thread execute method @getListUserOnServer
	 * Extends AsyncTask class with parameters: String for upon execution, JSONArray for result 
	 * @author LocDev
	 *
	 */
	class GetUserOnServer extends AsyncTask<String, Void, JSONArray> {

		@Override
		protected JSONArray doInBackground(String... params) {
			JSONArray jsonArray = getListUserOnServer(params[0]);
			if (jsonArray != null) {
				return jsonArray;
			}
			return null;
		}

		@Override
		protected void onPostExecute(JSONArray result) {
			if (result != null) {
				int len = result.length();
				mUserList.clear();
				for (int i = 0; i < len; i++) {
					JSONObject jObj;
					try {
						jObj = result.getJSONObject(i);
						mUserList.add(new DatabaseUser(jObj.getInt("user_id"), jObj.getString("username"), "", jObj.getString("email"), jObj.getString("phone_number"), "", 0, ""));
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				mAdapter = new UserListViewAdapter(ActivitySearchFriendOnline.this, mUserList);
				mUserListView.setAdapter(mAdapter);
			} else {
				
			}
		}
	}
	
	/**
	 * Function used to send request add new friend to server
	 * @param userId
	 * @param userRequestId
	 * @return
	 */
	private boolean sendFriendRequest(String userId, String userRequestId, String regId) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Constants.USER_ID, userId));
		params.add(new BasicNameValuePair(Constants.USER_REQUEST_ID, userRequestId));
		params.add(new BasicNameValuePair(Constants.PROPERTY_REG_ID, regId));
		HttpRequest request = new HttpRequest();
		String result = request.makeServiceCall(Constants.URL_FRIEND_REQUEST, HttpRequest.POST, params);
		return false;
	}
	
	/**
	 * 
	 * @author LocDev
	 *
	 */
	class SendFriendRequest extends AsyncTask<Void, Void, Void>{
		
		private String mUserId, mUserRequestId, mRegId;
		
		public SendFriendRequest(String userId,  String userRequestId, String regId){
			this.mUserId = userId;
			this.mUserRequestId = userRequestId;
			this.mRegId = regId;
		}

		@Override
		protected Void doInBackground(Void... params) {
			sendFriendRequest(mUserId, mUserRequestId, mRegId);
			return null;
		}
		
	}
}
